package com.sky.Push.Annotion;

import com.sky.Push.RequestHandler;
import com.sky.Push.Singleton;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 2017/6/15.
 */
@Component
public class AnnotionProcessor implements BeanPostProcessor {
    private static final Logger logger = LoggerFactory.getLogger(AnnotionProcessor.class);

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        Method[] methods = o.getClass().getDeclaredMethods();
        if(methods != null)
        {
            for(Method method : methods)
            {
                HandlerMapping handlerMapping = AnnotationUtils.findAnnotation(method,HandlerMapping.class);
                if(handlerMapping != null)
                {
                    int type = handlerMapping.type();

                    ObjectMethod om = new ObjectMethod();
                    om.setObj(o);
                    om.setMethod(method);

                    RequestHandler requestHandler = null;
                    try {
                        requestHandler = (RequestHandler) Singleton.getInstance(RequestHandler.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    requestHandler.methodMap.put(type,om);

                    logger.info("method {},type {}",method.toString(),type);
                }
            }
        }
        return o;
    }
}
